package com.unipay.hosp.receive;

import com.rabbitmq.client.Channel;
import com.unipay.common.rabbit.constant.MqConst;
import com.unipay.common.rabbit.service.RabbitService;
import com.unipay.hosp.service.ScheduleService;
import com.unipay.model.hosp.Schedule;
import com.unipay.vo.msm.MsmVo;
import com.unipay.vo.order.OrderMqVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author Chenmy
 * @Date 2023/7/9 18:39
 * @Desc TODO   封装mq监听器
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
                    key = {MqConst.ROUTING_ORDER}
            )
    )
    public void receive(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        if (null != orderMqVo.getAvailableNumber()) {
            // 下单成功：更新预约数
            Schedule schedule = scheduleService.getByID(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        } else {
            // 取消预约，更新预约数
            Schedule schedule = scheduleService.getByID(orderMqVo.getScheduleId());
            if (null != schedule){
                int availableNumber = schedule.getAvailableNumber().intValue() + 1;
                schedule.setAvailableNumber(availableNumber);
                scheduleService.update(schedule);
            }
        }
        // 发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (null != msmVo){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

}
